﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using elfam.web.Dao;
using elfam.web.Models;
using NHibernate;

namespace elfam.web.Paging
{
    public class ProductAdminListQueryBuilder
    {
        private SearchCriteria _searchCriteria;
        private string _hql;
        DaoTemplate _daoTemplate = new DaoTemplate();

        public ProductAdminListQueryBuilder(ProductAdminListSearchCriteria searchCriteria)
        {
            _searchCriteria = searchCriteria;
            
            _hql = @"select p, sum(inc.QuantityCurrent), max(inc.Date) 
                from Product p join p.Incomes inc 
                group by p.Id, p.Name, p.Description, p.ShortDescription, p.Price, p.Date, p.Category";
            
            if (searchCriteria.CategoryId.HasValue)
            {
                Category category = _daoTemplate.FindByID<Category>(searchCriteria.CategoryId);
                if (category != null)
                {
                    var subs = new List<Category>();
                    subs.Add(category);
                    subs.AddRange(category.AllSubCategories());
                    _hql += string.Format(" where p.Category in (:{0}) ", string.Join(",", subs.Select(x => x.Id.ToString()).ToArray()));    
                }
            }
        }

        public IList Execute(ISession session)
        {
            applyOrder();
            IQuery query = session.CreateQuery(_hql);
            applyPaging(query);
            return query.List();
        }

        private void applyPaging(IQuery query)
        {
            query.SetFirstResult(_searchCriteria.FirstResultIndex());
            query.SetMaxResults(_searchCriteria.PageSize);
        }

        private void applyOrder()
        {
            if (string.IsNullOrEmpty(_searchCriteria.SortExpression))
                return;
            string order = string.Format(" order by {0} {1} ", _searchCriteria.SortFieldDefault(), _searchCriteria.SortDirectionDefault());
            _hql += order;
        }
    }
}
